package com.boboPlanet.user.config;

import com.boboPlanet.comm.annotation.Token;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Description: TODO 自定义token解析器（需要将解析器配置在 RequestMappingHandlerAdapter中）
 * @Author: mis_wu
 * @Date: 2023/8/14
 * @Company TOKEN
 **/
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 是否支持某个参数，即判断参数上是否存在 @Token
     * @param parameter the method parameter to check
     * @return boolean
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Token token = parameter.getParameterAnnotation(Token.class);
        return token != null;
    }

    /**
     * 解析参数
     * @param parameter the method parameter to resolve. This parameter must
     * have previously been passed to {@link #supportsParameter} which must
     * have returned {@code true}.
     * @param mavContainer the ModelAndViewContainer for the current request
     * @param webRequest the current request
     * @param binderFactory a factory for creating {@link WebDataBinder} instances
     * @return Object
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, @NotNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Token token = parameter.getParameterAnnotation(Token.class);
        if (token != null){
            String alias = token.alias();
            if (StringUtils.isNotBlank(alias)){
                return webRequest.getHeader(alias);
            }
        }
        //获取请求头中token值
        return webRequest.getHeader("token");
    }
}
